package com.aaa.project.controller;


import com.aaa.entity.BBusinessInfo;
import com.aaa.project.service.GsortService;
import com.aaa.project.service.IBBusinessInfoService;
import com.aaa.util.MessageUtil;
import com.aaa.util.Result;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.apache.http.HttpResponse;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;


/**
 * <p>
 * 商家信息表 前端控制器
 * </p>
 *
 * @author zhangxuhui
 * @since 2023-01-07
 */
@RestController
@RequestMapping("/b-business-info")
public class BBusinessInfoController {
    @Resource
    private IBBusinessInfoService ibBusinessInfoService;
    @Resource
    private GsortService gsortService;

    //根据用户手机号获取信息
    @PostMapping("getBusinessByPhone/{telephone}")
    public BBusinessInfo getUserPhone(@PathVariable String telephone){
        QueryWrapper<BBusinessInfo> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("telephone",telephone);
        return ibBusinessInfoService.getOne(queryWrapper);
    }
//    //    商户注册
//    @PostMapping("BusinessRegister")
//    public Result bBusinessRegister(@RequestParam String telephone, @RequestParam  String password){
//
//        System.out.println(telephone);
//        QueryWrapper queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("telephone", telephone);
//        int telephoneCount = ibBusinessInfoService.count(queryWrapper);
//        System.out.println(telephoneCount);
//        Result result = new Result();
//        if (telephoneCount != 0) {
//            result.setCode(400);
//            result.setMsg("该手机号以注册");
//            return result;
//        } else {
//            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
//            String encode = encoder.encode(password);
//            BBusinessInfo bBusinessInfo = new BBusinessInfo();
//            bBusinessInfo.setTelephone(telephone);
//            bBusinessInfo.setPassword(encode);
//            ibBusinessInfoService.save(bBusinessInfo);
//            result.setCode(200);
//            result.setMsg("注册成功");
//            return result;
//        }
//    }
    @PostMapping("changePassword")
    public Result changePassword(String telephone,String newPassword){
        System.out.println("telephone="+telephone);
        System.out.println("newpassword="+newPassword);
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("telephone",telephone);
        BBusinessInfo bBusinessInfo = ibBusinessInfoService.getOne(queryWrapper);
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String encode = encoder.encode(newPassword);
        bBusinessInfo.setPassword(encode);
        boolean b = ibBusinessInfoService.updateById(bBusinessInfo);
        return new Result(b);
    }


    //    验证码
    @PostMapping("getCode")
    public Result getCode(String telephone){
        String host = "https://gyytz.market.alicloudapi.com";
        String path = "/sms/smsSend";
        String method = "POST";
        String appcode = "b1bff87d30ea444e8229f27e4db74dba";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        Map<String, String> querys = new HashMap<String, String>();
        Random random = new Random();
        int i = random.nextInt(10);
        int i1 = random.nextInt(10);
        int i2 = random.nextInt(10);
        int i3 = random.nextInt(10);
        String code = i + "" + i1 + "" + i2 + "" + i3 + "";
        querys.put("mobile", telephone);
        querys.put("param", "**code**:"+code+",**minute**:5");

//smsSignId（短信前缀）和templateId（短信模板），可登录国阳云控制台自助申请。参考文档：http://help.guoyangyun.com/Problem/Qm.html

        querys.put("smsSignId", "2e65b1bb3d054466b82f0c9d125465e2");
        querys.put("templateId", "908e94ccf08b4476ba6c876d13f084ad");
        Map<String, String> bodys = new HashMap<String, String>();


        try {
            /**
             * 重要提示如下:
             * HttpUtils请从\r\n\t    \t* https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java\r\n\t    \t* 下载
             *
             * 相应的依赖请参照
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
             */
            HttpResponse response = MessageUtil.doPost(host, path, method, headers, querys, bodys);
            System.out.println(response.toString());
            //获取response的body
            //System.out.println(EntityUtils.toString(response.getEntity()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result(code);
    }

    //查询登录的用户信息

    @GetMapping("getBusinessInfoByPhone")
    public Result<BBusinessInfo> getBusinessByPhone(@RequestParam("user_name") String name){
        System.out.println("从前端拿到的商家用户名是"+name);
        QueryWrapper queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("telephone",name);
        System.out.println("准备查找数据");
//        System.out.println(queryWrapper);
        BBusinessInfo bBusinessInfo = ibBusinessInfoService.getOne(queryWrapper);
        System.out.println(bBusinessInfo);
        return  new Result(bBusinessInfo);
    }


//    商家修改
    @PostMapping("changeBusinessInfoByphone")
    public Result changeBusinessInfoByphone(@RequestBody BBusinessInfo bBusinessInfo){
        UpdateWrapper<BBusinessInfo> updateWrapper = new UpdateWrapper();
        updateWrapper.eq("id",bBusinessInfo.getId()).set("state",bBusinessInfo.getState());
        ibBusinessInfoService.update(updateWrapper);
        HashMap<String,Object> changeMap = new HashMap<>();
        changeMap.put("id",bBusinessInfo.getId());
        changeMap.put("state",bBusinessInfo.getState());
        QueryWrapper<BBusinessInfo> queryWrapper=new QueryWrapper<>();
        queryWrapper.allEq(changeMap);
        int dataCount = ibBusinessInfoService.count(queryWrapper);
        BBusinessInfo businessInfoServiceOne = ibBusinessInfoService.getOne(queryWrapper);
        Result result = new Result();
        result.setData(businessInfoServiceOne);
        System.out.println(dataCount);
        if(dataCount!=0){
            return  result;
        }else {
            result.setMsg("修改失败");
            return result;
        }
    }

        /**
         * 用户入住商家
         */
        @PostMapping("storeinsert")
        public Result storeinsert(BBusinessInfo bBusinessInfo){
            bBusinessInfo.setStatus(2);
            bBusinessInfo.setApplicationdate(String.valueOf(LocalDateTime.now()));
            return new Result<>(ibBusinessInfoService.saveOrUpdate(bBusinessInfo));
        }

    @GetMapping("findAllSort")
    public Result findAllSort(){
        return new Result<>(gsortService.list());
    }

//    商家密码修改

}

